package com.heima.common.contentsecurity;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Slf4j
//@Component
public class ContentSecurityCheck {
    public static final String API_KEY = "NZ83evBuGFB5HDN70FBsCKSC";
    public static final String SECRET_KEY = "8vWLIM5ZRr5FHaAX3AfrGW6TIzpAIGto";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
            .readTimeout(300, TimeUnit.SECONDS)
            .build();

    /**
     * 检测文本内容
     *
     * @param text
     * @return
     * @throws IOException
     */
    public boolean detectText(String text) throws Exception {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "text=" + URLEncoder.encode(text, "UTF-8"));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String body1 = response.body().string();

        // 解析JSON响应判断是否合规
        JSONObject jsonResult = new JSONObject(body1);

        // 检查是否存在违规内容（根据百度API文档，通常通过conclusionType判断）
        int conclusionType = jsonResult.optInt("conclusionType", 0);
        log.info("百度审核结果：{}", body1);
        // conclusionType为1表示合规，其他值（2/3/4）表示不合规或疑似违规
        boolean b = conclusionType == 1;
        if (b) {
            log.info("文本合规");
        } else {
            log.info("文本不合规");
        }
        return b;
    }

    /**
     * 检测图片 - 使用Base64编码方式
     *
     * @param imageUrl 图片的URL路径
     * @return 图片是否合规
     * @throws Exception
     */
    public boolean inspectTheImage(String imageUrl) throws Exception {
        log.info("百度审核图片URL：{}", imageUrl);

        // 1. 先下载图片并转换为Base64编码
        String base64Image = getImageAsBase64(imageUrl);

        // 2. 使用Base64编码进行审核
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String base64Param = "image=" + URLEncoder.encode(base64Image, "UTF-8"); // 注意参数名改为image

        RequestBody body = RequestBody.create(mediaType, base64Param);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String body1 = response.body().string();
        log.info("百度审核结果：{}", body1);

        // 解析JSON响应判断是否合规
        JSONObject jsonResult = new JSONObject(body1);

        // 检查是否存在违规内容（根据百度API文档，通常通过conclusionType判断）
        int conclusionType = jsonResult.optInt("conclusionType", 0);
        // conclusionType为1表示合规，其他值（2/3/4）表示不合规或疑似违规
        boolean b = conclusionType == 1;
        if (b) {
            log.info("图片合规，{}", imageUrl);
        } else {
            log.info("图片不合规,{}", imageUrl);
        }
        return b;
    }

    /**
     * 从图片URL获取图片内容并转换为Base64编码
     *
     * @param imageUrl 图片的URL路径
     * @return 图片的Base64编码字符串
     * @throws IOException
     */
    private String getImageAsBase64(String imageUrl) throws IOException {
        Request request = new Request.Builder()
                .url(imageUrl)
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("无法获取图片: " + response);
            }

            byte[] imageBytes = response.body().bytes();
            return Base64.getEncoder().encodeToString(imageBytes);
        }
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws Exception {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}